import { Component, NgZone, ViewChild, OnInit, Inject } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { CdkTextareaAutosize } from '@angular/cdk/text-field';
import { TranslateService } from '@ngx-translate/core';
import { ActionTypes, ObjectTypes } from '../../models/wdl-types';

import * as _ from 'lodash';

@Component({
  selector: 'app-bed-dialog',
  templateUrl: './bed-dialog.component.html',
  styleUrls: ['./bed-dialog.component.css']
})
export class BedDialogComponent implements OnInit {
  formGroup: FormGroup;
  item: any;
  title = '';
  type: ObjectTypes;

  // could be add, modify, read
  mode = ActionTypes.ADD;
  disabled = false;

  @ViewChild('autosize') autosize: CdkTextareaAutosize;

  constructor(@Inject(MAT_DIALOG_DATA) private dialogData: any,
              public dialogRef: MatDialogRef<BedDialogComponent>,
              fb: FormBuilder,
              private ngZone: NgZone,
              private translate: TranslateService,
              private dialog: MatDialog) {
    this.item = dialogData.item;
    this.mode = dialogData.mode;
    this.type = dialogData.type;

    if (this.mode === ActionTypes.ADD) {
      this.title = this.translate.get('add')['value'] + this.translate.get(this.getType())['value'];
    } else if (this.mode === ActionTypes.MODIFY) {
      this.title = this.translate.get('edit')['value'];
    }

    this.formGroup = fb.group({
      name: [
        '',
        [
          Validators.required,
          Validators.maxLength(128)
        ]
      ]
    });

    if (this.mode !== ActionTypes.ADD) {
      _.forEach(this.formGroup.controls, (value, key) => {
        value.value = this.item[this.getType() + (key === 'name' ? 'Name' : key)];
      });
    }
  }

  getType(): string {
    switch (this.type) {
    case ObjectTypes.BUILDING:
      return 'building';
    case ObjectTypes.LEVEL:
      return 'level';
    case ObjectTypes.ROOM:
      return 'room';
    case ObjectTypes.BED:
      return 'bed';
    }
  }

  disableSubmit() {
    return this.formGroup.invalid || (this.mode === ActionTypes.MODIFY && !this.formGroup.dirty);
  }

  submit() {
    const data = {};
    _.forEach(this.formGroup.value, (value, key) => {
      if (key === 'name') {
        data[this.getType() + 'Name'] = _.trim(value);
      } else {
        data[key] = _.trim(value);
      }
    });

    this.dialogRef.close(data);
  }

  ngOnInit() {
  }
}
